#include <asl_core.h>
#include <lib_curl.h>

static size_t lib_curl_write_cb(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    lib_curl_mem_t *mem;
    mem = (lib_curl_mem_t *) userp;
    mem->memory = realloc(mem->memory, mem->size + realsize + 1);
    if (mem->memory == NULL) {
        return 0;
    }
    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}

int lib_curl_get(const char *url, lib_curl_mem_t *chunk) {
    CURL *curl;
    CURLcode res;
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl == NULL) {
        curl_global_cleanup();
        return RET_FAILURE;
    }
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, LIB_CURL_TIME_OUT);
    curl_easy_setopt(curl, CURLOPT_HEADER, 0);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, lib_curl_write_cb);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *) chunk);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, LIB_CURL_AGENT);
    res = curl_easy_perform(curl);
    if (res != CURLE_OK) {
        curl_easy_cleanup(curl);
        curl_global_cleanup();
        return RET_FAILURE;
    }
    curl_easy_cleanup(curl);
    curl_global_cleanup();
    return RET_SUCCESS;
}